import React, { memo, useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { Button, Input, NavBar, TextArea, Toast } from "antd-mobile";
import AvatarSelector from "@/components/AvatarSelector/AvatarSelector";
import ListBlock from "@/components/ListBlock/ListBlock";
import store from "@/store";
import { fetchRegisterAction } from "@/store/modules/user";
import SeekerInfoWrapper from "./style";

const SeekerInfo = memo((props) => {
  const navigate = useNavigate();
  const dispatch = useDispatch();

  let [userInfo, setUserInfo] = useState({
    title: "",
    desc: "",
  });

  useEffect(() => {
    if (store.getState().user.type !== "seeker") {
      navigate("/register");
    }
  });

  function back() {
    history.go(-1);
  }

  function updateUserInfo(k, v) {
    let newobj = {
      ...userInfo,
      [k]: v,
    };
    setUserInfo(newobj);
  }

  async function save() {
    let storeUserInfo = store.getState().user;
    // 上一步填写的资料获取
    let obj = {
      pwd: storeUserInfo.pwd,
      type: storeUserInfo.type,
      user: storeUserInfo.user,
    };
    let newObj = Object.assign({}, obj, userInfo);
    dispatch(fetchRegisterAction(newObj))
      .then((res) => {
        if (res.payload.code === 2000) {
          Toast.show({
            content: "注册成功",
          });
          navigate("/login");
        }
      })
      .catch((err) => {
        Toast.show({
          content: "注册失败",
        });
      });
  }

  return (
    <SeekerInfoWrapper>
      <NavBar mode="dark" onBack={back} className="navbar">
        求职者完善信息
      </NavBar>
      <div className="avatar">
        <AvatarSelector updateUserInfo={updateUserInfo}></AvatarSelector>
      </div>

      <div className="list">
        <ListBlock title="求职岗位">
          <Input
            placeholder="请输入内容"
            value={userInfo.title}
            onChange={(val) => updateUserInfo("title", val)}
          />
        </ListBlock>
        <ListBlock title="个人简介">
          <TextArea
            placeholder="请输入内容"
            autoSize={{ minRows: 3, maxRows: 5 }}
            value={userInfo.desc}
            onChange={(val) => updateUserInfo("desc", val)}
          />
        </ListBlock>
      </div>
      <div className="btnContainer">
        <Button
          className="btn"
          color="primary"
          onClick={() => {
            save();
          }}
        >
          保存
        </Button>
      </div>
    </SeekerInfoWrapper>
  );
});

export default SeekerInfo;
